from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.notice_center.models.nc_log_alarm_notice import NCLogAlarmNotice
from app.manage_notice.models.manage_notice_team import ManageNoticeTeam
from setting import config


class NCLogAlarmNoticeHandler():
    """  LogAlarmNotice Handler
    """
    def __init__(self):
        pass


    def get_log_alarm_notice_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取日志告警通知信息
        """
        try:
            field_info = {field: value}
            order_info = {"name": "asc"}
            result = NCLogAlarmNotice.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get log alarm notice search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get log alarm notice search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result



    def get_log_alarm_notice_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取日志告警通知信息
        """
        try:
            result = NCLogAlarmNotice.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get log alarm notice match, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get log alarm notice match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result





    def add_log_alarm_notice(self, db: Session, data: dict):
        """
        创建日志告警通知信息
        """
        try:
            log_alarm_notice_object = NCLogAlarmNotice.get_object_by_name(db, data["name"])
            if log_alarm_notice_object:
                # 如果存在， 则异常返回
                logger.error(f"add log alarm notice failed,{data['name']} was exist")
                return False

            # 创建日志告警通知
            result = NCLogAlarmNotice.add(db, data)
            if not result:
                logger.error(f"add log alarm notice to database failed")
                return False

        except Exception as e:
            message = f"add log alarm notice error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




    def update_log_alarm_notice(self, db: Session, data: dict):
        """
        修改日志告警通知信息
        """
        try:
            log_alarm_notice_object = NCLogAlarmNotice.get_object_by_uuid(db, data["uuid"])
            if not log_alarm_notice_object:
                # 如果不存在， 则异常返回
                logger.error(f"update log alarm notice failed,{data['uuid']} not exist")
                return False

            result = NCLogAlarmNotice.update(db, data)
            if not result:
                logger.error(f"update log alarm notice to database failed")
                return False
        except Exception as e:
            message = f"update log alarm notice error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def update_log_alarm_maintain(self, db: Session, data: dict):
        """
        修改日志告警通知信息
        """
        try:
            log_alarm_notice_object = NCLogAlarmNotice.get_object_by_name(db, data['name'])
            if not log_alarm_notice_object:
                # 如果不存在， 则新建
                data["server_type"] = config.NOTICE_CENTER_LOG_SERVER_TYPE
                data["level"] = config.NOTICE_CENTER_LOG_LEVEL
                data["department"] = config.NOTICE_CENTER_LOG_DEPARTMENT
                
                notice_team_info = ManageNoticeTeam.get_object_info_by_name(db, config.NOTICE_CENTER_LOG_TEAM)
                if not notice_team_info:
                    data["notice_teams_uuid"] = [1]
                else:
                    data["notice_teams_uuid"] = [notice_team_info["uuid"]]
                    
                logger.info(f"server:{data['name']} not exist, set default info:{data}")
                result = NCLogAlarmNotice.add(db, data)
                if not result:
                    logger.error(f"add log alarm maintain to database failed")
                    return False

                logger.info(f"add log alarm maintain success")
            else:
                # 如果存在，则更新
                data["uuid"] = log_alarm_notice_object.uuid
                result = NCLogAlarmNotice.update(db, data)
                if not result:
                    logger.error(f"update log alarm maintain to database failed")
                    return False
                
                logger.info(f"update log alarm maintain success")
        except Exception as e:
            message = f"update log alarm maintain error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




    def delete_log_alarm_notice(self, db: Session, data: dict):
        """
        删除日志告警通知信息
        """
        try:
            log_alarm_notice_object = NCLogAlarmNotice.get_object_by_uuid(db, data['uuid'])
            if not log_alarm_notice_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete log alarm notice failed, uuid:{data['uuid']} not exist")
                return False

            # 删除通知用户
            NCLogAlarmNotice.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete log alarm notice uuid:{data['uuid']}  error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




